﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using Android.App;
using Android.Content;
using Android.OS;
using Android.Runtime;
using Android.Views;
using Android.Widget;
using Android.Webkit;
using LinkNote.Model;
using net.sgoliver;
using Android.Util;
using LinkNote.Core;

namespace LinkNote
{
    [Activity(Label = "笔记编辑")]
    public class NoteEditorActivity : Activity
    {
        private TextView txtTitle;
        private TextView txtAuthor;
        private TextView txtSource;
        private TextView txtCreateTime;
        private RichTextEditor editor;

        protected override void OnCreate(Bundle bundle)
        {
            if (MainActivity.loginUser == null)
            {
                this.Finish();
                StartActivity(typeof(LoginActivity));
                return;
            } 
            base.OnCreate(bundle);

            // Create your application here
            this.RequestWindowFeature(WindowFeatures.NoTitle);
            SetContentView(Resource.Layout.noteeditor);
            WebQuery.Init(this);

            txtTitle = this.FindViewById(Resource.Id.txtTitle) as TextView;
            txtAuthor = this.FindViewById(Resource.Id.txtAuthor) as TextView;
            txtSource = this.FindViewById(Resource.Id.txtSource) as TextView;
            txtCreateTime = this.FindViewById(Resource.Id.txtCreateTime) as TextView;
            editor = this.FindViewById(Resource.Id.editor) as RichTextEditor;
            editor.Editable = true;

            ImageButton btn = this.FindViewById(Resource.Id.btnClose) as ImageButton;
            btn.Click += delegate
            {
                MainActivity ma = MainActivity.Instance;
                ma.ShowNoteClass();
                ma.ShowNoteList();
                ma.SelectedNote = this.SelectedNote;
                WebQuery.Init(ma);
                this.Finish();
            };

            btn = this.FindViewById(Resource.Id.btnSave) as ImageButton;
            btn.Click += delegate
            {
                Save();
            };

            int fileid = this.Intent.GetIntExtra("fileid", 0);
            LinkNoteFile file = DBHelper.sqlitedb.Find<LinkNoteFile>(fileid);
            if (file == null)
            {
                txtCreateTime.Text = DateTime.Now.ToString("HH:mm");
            }
            else
                SelectedNote = file;

            //笔记本
            Button noteClassButton = FindViewById<Button>(Resource.Id.btnNoteClass);
            noteClassButton.Click += (v, e) =>
            {
                if(this.SelectedNote == null)
                {
                    AlertDialog.Builder alert2 = new AlertDialog.Builder(this);
                    alert2.SetMessage("请先保存笔记！")
                          .SetNegativeButton("确定", (IDialogInterfaceOnClickListener)null)
                          .Show();
                }
                else
                    NoteViewActivity.ShowClassChooseDialog(this, this.SelectedNote);
            };

            //标签
            Button lableButton = FindViewById<Button>(Resource.Id.btnNoteLabel);
            lableButton.Click += (v, e) =>
            {
                if (this.SelectedNote == null)
                {
                    AlertDialog.Builder alert2 = new AlertDialog.Builder(this);
                    alert2.SetMessage("请先保存笔记！")
                          .SetNegativeButton("确定", (IDialogInterfaceOnClickListener)null)
                          .Show();
                }
                else
                    NoteViewActivity.ShowLabelChooseDialog(this, this.SelectedNote, delegate
                    {
                        this.SelectedNote = this.SelectedNote;
                    });
            };
        }

        private void Save()
        {
            if (selectedNote == null)
            {
                selectedNote = new LinkNoteFile();
                selectedNote.createTime = DateTime.Now;
                selectedNote.revision = "1";
                selectedNote.UserID = MainActivity.loginUser.userId;

                NoteClass nc = MainActivity.Instance.SelectedClass;
                if (nc != null && nc.catalogueid > 0)
                    selectedNote.ClassID = nc.catalogueid;
                else
                    selectedNote.ClassID = 0;//放到默认笔记本
            }
            MainBody mb = editor.GetMainBodyData();
            selectedNote.title = txtTitle.Text;
            selectedNote.source = txtSource.Text;
            selectedNote.modifyTime = DateTime.Now;
            selectedNote.author = txtAuthor.Text;
            //selectedNote.tags = string.Format("{0},{1}", txtSource.Text, txtAuthor.Text);
            selectedNote.size = mb.body.Length;
            DBHelper.sqlitedb.InsertOrUpdate(selectedNote);

            mb.noteid = selectedNote.noteid == 0 ? selectedNote.ID : selectedNote.noteid;
            DBHelper.sqlitedb.InsertOrUpdate(mb);
            selectedNote = DBHelper.sqlitedb.Find<LinkNoteFile>(selectedNote.ID);

            //List<AudioBlock> medias = editor.GetMediaData();
            //foreach (AudioBlock b in medias)
            //    b.noteid = selectedNote.noteid;
            //DBHelper.sqlitedb.InsertOrUpdateAll(medias, true);

            //List<PictureBlock> pictures = editor.GetPictureData();
            //foreach (PictureBlock pb in pictures)
            //    pb.noteid = selectedNote.noteid;
            //DBHelper.sqlitedb.InsertOrUpdateAll(pictures, true);

            List<AttachmentBlock> attachs = editor.GetAttachmentData();
            foreach (AttachmentBlock ab in attachs)
                ab.noteid = selectedNote.noteid == 0 ? selectedNote.ID : selectedNote.noteid;
            DBHelper.sqlitedb.InsertOrUpdateAll(attachs, true);

            Toast.MakeText(this, "保存到本地成功", ToastLength.Long);
            //保存到服务器
            WebQuery.SaveNote(selectedNote.noteid, selectedNote.revision, selectedNote.title, selectedNote.abstra,
                selectedNote.MainbodyFromDB.body, selectedNote.ClassID, selectedNote.author, selectedNote.source, selectedNote.tags, "保存到服务器", delegate(QueryResult result, SaveNoteResult file)
                    {
                        if (result.status == "SUCCESS")
                        {
                            //更正noteid
                            selectedNote.noteid = file.noteid;
                            DBHelper.sqlitedb.Update(selectedNote);

                            //更正noteid
                            mb = editor.GetMainBodyData();
                            mb.noteid = file.noteid;
                            DBHelper.sqlitedb.InsertOrUpdate(mb);

                            //更正noteid
                            attachs = editor.GetAttachmentData();
                            foreach (AttachmentBlock ab in attachs)
                                ab.noteid = file.noteid;
                            DBHelper.sqlitedb.InsertOrUpdateAll(attachs, true);

                            Toast.MakeText(this, "保存到服务器成功", ToastLength.Long);
                        }
                    });
        }

        private LinkNoteFile selectedNote;
        public LinkNoteFile SelectedNote
        {
            get
            {
                return selectedNote;
            }
            set
            {
                selectedNote = value;
                if (selectedNote != null)
                    ShowNoteView(selectedNote);
            }
        }

        private void ShowNoteView(LinkNoteFile file)
        {
            txtTitle.Text = file.title;
            txtAuthor.Text = file.author;
            txtSource.Text = file.source;
            //string[] tags = file.tags.Split(',');
            //txtAuthor.Text = tags[0];
            //txtSource.Text = tags[1];

            txtCreateTime.Text = "创建时间：" + file.createTime.ToLongDateString() + " " + file.createTime.ToString("HH:mm");
            editor.LoadData(file);
        }

        public override void OnCreateContextMenu(IContextMenu menu, View v, IContextMenuContextMenuInfo info)
        {
            editor.OnCreateContextMenu(menu, v, info);
            base.OnCreateContextMenu(menu, v, info);
        }

        public override bool OnContextItemSelected(IMenuItem item)
        {
            editor.OnContextItemSelected(item);
            return base.OnOptionsItemSelected(item);
        }

        protected override void OnActivityResult(int requestCode, Result resultCode, Intent data)
        {
            base.OnActivityResult(requestCode, resultCode, data);
            editor.OnActivityResult(requestCode, resultCode, data);
        }

        protected override void OnPause()
        {
            base.OnPause();
            editor.OnActivityPause();
        }
    }

    /*
        class MyJavaScriptInterface : Java.Lang.Object
        {
            public void showHTML(String html)
            {
                new AlertDialog.Builder(null)
                    .SetTitle("HTML")
                    .SetMessage(html)
                    //.SetPositiveButton(Resource.String.Hello, null)  
                .SetCancelable(false)
                .Create()
                .Show();
            }
        }

        class MyWebViewClient : WebViewClient
        {
            public void onPageFinished(WebView view, String url)
            {
                view.LoadUrl("javascript:window.HTMLOUT.showHTML('<head>'+document.getElementsByTagName('html')[0].innerHTML+'</head>');");
            }
        }

        WebView browser = (WebView)FindViewById(Resource.Id.browser);
        browser.Settings.JavaScriptEnabled = true;

        browser.AddJavascriptInterface(new MyJavaScriptInterface(), "HTMLOUT");

        browser.SetWebViewClient(new MyWebViewClient());
        browser.LoadUrl("http://lexandera.com/files/jsexamples/gethtml.html");
     * */
}